#include "imageuploadworker.h"
#include "remotetablemodel.h"
#include "imageuploader.h"

#include <QEventLoop>
#include <QDebug>

QList<QThread *> ImageUploadManager::activeThreads;
QMutex ImageUploadManager::threadMutex;

ImageUploadWorker::ImageUploadWorker(RemoteTableModel *imagemodel, const QStringList &imagePaths, const UploadConfig &config, QObject *parent)
    : QObject(parent), m_imagemodel(imagemodel),
      m_imagePaths(imagePaths), m_config(config)
{
}

ImageUploadWorker::ImageUploadWorker(RemoteTableModel *imagemodel, const QList<QByteArray> &imageDataList, const QList<QString> &imageIdentifiers, const UploadConfig &config, QObject *parent)

    : QObject(parent), m_imagemodel(imagemodel),
      m_imageDataList(imageDataList), m_imageIdentifiers(imageIdentifiers),
      m_config(config)
{
}

void ImageUploadWorker::processImageFromPath(const QString &imagePath)
{
    QByteArray imageData = getImageData(imagePath);
    if (imageData.isEmpty())
    {
        emit imageFailed(imagePath, "无法读取图片文件");
        return;
    }

    uploadImageData(imageData, imagePath);
}
void ImageUploadWorker::processImageData(const QByteArray &imageData, const QString &identifier)
{
    if (imageData.isEmpty())
    {
        saveImageToDatabase(identifier, "图片数据为空");
        // emit imageFailed(identifier, "图片数据为空");
        return;
    }

    uploadImageData(imageData, identifier);
}
void ImageUploadWorker::uploadImageData(const QByteArray &imageData, const QString &identifier)
{
    ImageUploader uploader;
    QEventLoop loop;

    connect(&uploader, &ImageUploader::uploadFinished, &loop, &QEventLoop::quit);
    connect(&uploader, &ImageUploader::uploadFailed, &loop, &QEventLoop::quit);

    uploader.uploadImage(m_imagemodel->getTableName(), imageData);
    loop.exec();

    if (!uploader.lastUrl().isEmpty())
    {
        saveImageToDatabase(identifier, uploader.lastUrl());
        emit imageUploaded(identifier, uploader.lastUrl());
    }
    else
    {
        saveImageToDatabase(identifier, "图片上传失败");
        emit imageFailed(identifier, "图片上传失败");
    }
}

void ImageUploadWorker::saveImageToDatabase(const QString &identifier, const QString &url)
{
    QVariantMap rowData = m_config.fixedFields; // 复制固定字段
    if (!m_config.foreignKeyField.isEmpty())
    {
        rowData[m_config.foreignKeyField] = m_config.foreignKeyValue;
    }
    rowData[m_config.imageUrlField] = url;

    QEventLoop dbLoop;
    bool insertSuccess = false;
    m_imagemodel->insertRowWithCallback(rowData, [&](int imageId)
                                        {
            if (imageId != -1) {
                insertSuccess = true;
            } else {
                qDebug() << "图片数据插入失败:" << identifier;
            }
            dbLoop.quit(); });

    dbLoop.exec();

    if (!insertSuccess)
    {
        emit imageFailed(identifier, "数据库插入失败");
    }
}

QByteArray ImageUploadWorker::getImageData(const QString &imagePath)
{
    QFile file(imagePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        qWarning() << "无法打开图片文件:" << imagePath;
        return QByteArray();
    }
    return file.readAll();
}

void ImageUploadWorker::startUpload()
{
    // 处理路径模式
    if (!m_imagePaths.isEmpty())
    {
        for (const QString &imagePath : m_imagePaths)
        {
            processImageFromPath(imagePath);
        }
    }

    // 处理原始数据模式
    if (!m_imageDataList.isEmpty())
    {
        for (int i = 0; i < m_imageDataList.size(); ++i)
        {
            processImageData(m_imageDataList[i], m_imageIdentifiers.value(i, "Unnamed"));
        }
    }
    else
    {
        processImageData(QByteArray(), "Unnamed");
    }

    emit finished();
}